package handlers

import (
	"class08/model"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// 创建代办事项
func (h *Handlers) CreateTodo(c *gin.Context) {
	//获取传入的json数据并进行处理
	var todo model.Todo
	err := c.BindJSON(&todo)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	c.GetInt("userID")
	//如果传输过来的数据已经成功赋值
	todo.UserID = c.GetInt("userID")
	h.DB.Create(&todo)
	c.JSON(http.StatusCreated, todo)

}

// 查询
func (h *Handlers) GetTodos(c *gin.Context) {
	var todos []model.Todo
	//查询userid有多少待办事项
	h.DB.Where("user_id = ?", c.GetInt("userID")).Find(&todos)
	c.JSON(http.StatusOK, todos)

}

// 更新
func (h *Handlers) UpdateTodo(c *gin.Context) {
	//查看数据是否存在
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	var updateTodo model.Todo
	err = c.BindJSON(&updateTodo)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
	}
	h.DB.Model(&model.Todo{}).Where("id = ?", id).Updates(updateTodo)
	c.JSON(http.StatusOK, updateTodo)

}

// 删除操作
func (h *Handlers) DeleteTodo(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	var todo model.Todo
	h.DB.Where("id = ? AND user_id = ?", id, c.GetInt("userID")).First(&todo)
	if todo.ID == 0 {
		//没有查到
		c.JSON(http.StatusNotFound, gin.H{"error": "todo not found"})
		return
	}
	h.DB.Where("id = ?", id).Delete(&model.Todo{})
	c.JSON(http.StatusOK, gin.H{"message": "todo delete"})
}
